﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;

namespace VietTrips.Domain.Helpers
{
    public static class CacheProvider
    {
        public static int TimeCache = 180;

        public static T Get<T>(string cacheId, Func<T> getItemCallback) where T : class
        {
            var item = HttpRuntime.Cache.Get(cacheId) as T;
            if (item == null)
            {
                item = getItemCallback();
                HttpContext.Current.Cache.Add(cacheId, item, null,
                        DateTime.Now.AddSeconds(TimeCache), 
                        TimeSpan.Zero, 
                        CacheItemPriority.Default, null);
            }
            return item;
        }

        public static T Get<T>(string cacheId, DateTime expriredTime, Func<T> getItemCallback) where T : class
        {
            var item = HttpRuntime.Cache.Get(cacheId) as T;
            if (item == null)
            {
                item = getItemCallback();
                HttpContext.Current.Cache.Add(cacheId, item, null,
                        expriredTime,
                        TimeSpan.Zero,
                        CacheItemPriority.Default, null);
            }
            return item;
        }

        public static T ClearAndGetNewCache<T>(string cacheId, DateTime expriredTime, Func<T> getItemCallback) where T : class
        {
            HttpRuntime.Cache.Remove(cacheId);
            var item = getItemCallback();
            HttpContext.Current.Cache.Add(cacheId, item, null,
                        expriredTime,
                        TimeSpan.Zero,
                        CacheItemPriority.Default, null);
            return item;
        }
    }
}
